angular.module('starter.controllers', ['ionic-datepicker'])

.controller('DashCtrl', function($scope,OrderService,$rootScope){
        $rootScope.validateUser();
        function ContentController($scope, $ionicSideMenuDelegate) {
            $scope.toggleLeft = function() {
                $ionicSideMenuDelegate.toggleLeft();
            };
        }
        function getOrders($status,$date){
            $rootScope.showLoading();
            OrderService.getOrderList({status:$status,date:$date}).$promise.then(function (result) {
                $rootScope.hideLoading();
                $scope.orders = result.data;
                console.log($scope.orders );
            });
        }

        $scope.status = 'processing';
        $scope.date = $rootScope.format_date(new Date(),'delivery_date');

        getOrders($scope.status,$scope.date);

        $scope.showMsg=function(msg){
            $rootScope.showAlert('Message',msg);
        }

        $scope.logout = function(){
            localStorage.setItem("username", JSON.stringify(''));
            $rootScope.go('login');
        }

        $scope.doRefresh = function() {
            OrderService.getOrderList({status:$scope.status,date:$scope.date}).$promise.then(function (result) {
                $rootScope.hideLoading();
                $scope.orders = result.data;
                console.log($scope.orders );
            }).finally(function() {
                // Stop the ion-refresher from spinning
                $scope.$broadcast('scroll.refreshComplete');
            });

        };

        $scope.confirmOrder = function(order_id){
            $rootScope.showLoading();
            OrderService.driverConfirmOrder({order_id:order_id,username:localStorage.getItem("username")}).$promise.then(function (result) {
                $rootScope.hideLoading();
                if(result.success != 1){
                    $rootScope.showAlert('Error',result.error_msg);
                }else{
                    $rootScope.showAlert('Success','Confirm order success');
                }
                $scope.doRefresh();
            });
        }

        $scope.disprocessOrder = function(order_id){
            $rootScope.showLoading();
            OrderService.disprocessOrder({order_id:order_id}).$promise.then(function (result) {
                $rootScope.hideLoading();
                if(result.success != 1){
                    $rootScope.showAlert('Error',result.error_msg);
                }else{
                    $rootScope.showAlert('Success','Disprocess order success');
                }
                $scope.doRefresh();
            });
        }

        $scope.goGoogleMap = function(street,city,region){
            var url = "http://maps.google.com/?q="+encodeURI(street) +encodeURI(city)+','+encodeURI(region);
            console.log(url);
            $rootScope.outerLink(url);
        }

        $scope.currentDate = new Date();
        $scope.minDate = new Date(2015, 6, 1);
        $scope.maxDate = new Date(2020, 6, 31);

        $scope.datePickerCallback = function (val) {
            if (!val) {
                console.log('Date not selected');
            } else {
                $scope.date = $rootScope.format_date(val,'delivery_date');
                getOrders($scope.status,$scope.date);
            }
        };

    })

.controller('LoginCtrl', function($scope,UserService,$rootScope,$state) {
    $scope.checkDriverUser = function(user){
        $rootScope.showLoading();
        UserService.checkDriverUser({username:user.username,password:user.password}).$promise.then(function (result) {
            $rootScope.hideLoading();
            if(result.success == 1){
                localStorage.setItem("username", JSON.stringify(user.username));
                $state.go("tab.dash" ,{}, { reload: true });
            }else{
                $rootScope.showAlert('Login Failed',result.error_msg);
            }
        });
    }
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope,$rootScope) {
  $rootScope.validateUser();
  $scope.settings = {
    enableFriends: true
  }
})

.controller('OrderDetailCtrl', function($scope,$stateParams,$rootScope,OrderService,$ionicPopup,$state,OrderStatusService) {
    $rootScope.validateUser();
    $rootScope.showLoading();
    OrderService.getOrderDetail({increment_id:$stateParams.increment_id}).$promise.then(function (result) {
        $rootScope.hideLoading();
        $scope.order = result.data;
        $scope.out_of_stock = 0;
        $scope.substitute = 0;
        $scope.original_tax = $scope.order.order_tax;
        $scope.tax = 0;
        for(var g in $scope.order.goods){
            if($scope.order.goods[g]['item_status'] == 'out_of_stock'){
                $scope.out_of_stock -= $scope.order.goods[g]['row_total'];
            }else if($scope.order.goods[g]['item_status'] == 'substitute'){
                $scope.substitute += -$scope.order.goods[g]['row_total'] + $scope.order.goods[g]['sub_price']*$scope.order.goods[g]['sub_volume'];
                $scope.tax += Math.round(($scope.order.goods[g]['sub_price']*$scope.order.goods[g]['sub_volume']*$scope.order.goods[g]['tax_percent']))/100;
            }else{
                $scope.tax += parseFloat($scope.order.goods[g]['tax_amount']);
            }
            if ($scope.order.goods[g].store_price == null || $scope.order.goods[g].store_price == ''){
                $scope.order.goods[g].store_price = $scope.order.goods[g].price;
            }
            console.log($scope.tax);
//            $scope.original_tax += $scope.order.goods[g]['tax_amount'];
        }
        $scope.total = parseFloat($scope.order.grand_total) - $scope.original_tax + $scope.out_of_stock + $scope.substitute + $scope.tax;
        $scope.original_grand_total = parseFloat($scope.order.grand_total);
        $scope.change = $scope.total - $scope.original_grand_total;
        console.log($scope.order );
    });

    $scope.showMsg=function(msg){
        $rootScope.showAlert('Message',msg);
    };

    $scope.completeOrder = function(order_id){
        var lack_num = 0
        for(var i in $scope.order.goods){
            if ($scope.order.goods[i]['item_status'] == '' || $scope.order.goods[i]['item_status'] == null){
                lack_num ++;
                var goods_id = $scope.order.goods[i]['item_id'];
            }
        }

        if(lack_num > 0){
            var warnPopup = $ionicPopup.confirm({
                title: 'WARNING',
                template: 'You still have '+lack_num+' items not picked up, would you like to proceed? If yes, those items will be marked as "out of stock” automatically.'
            });

            warnPopup.then(function(res) {
                if(res) {
                    var confirmPopup = $ionicPopup.confirm({
                        title: 'Confirm',
                        template: 'Are you sure you want to complete this order?'
                    });

                    confirmPopup.then(function(res) {
                        if(res) {
                            $rootScope.showLoading();
                            OrderService.completeOrder({order_id:order_id}).$promise.then(function (result) {
                                $rootScope.hideLoading();
                                $scope.result = result.data;
                                if(result.success == 1){
                                    OrderStatusService.changeOrderStatus({orderid:order_id,order_status:'in_transit'}).$promise.then(function (res) {
                                        console.log(res);
                                    });
                                    $rootScope.showAlert('Success',"You have completed this order.");
                                }
                                console.log($scope.result );
                            });
                        }
                    });
                }else{
                    $state.go('item-detail',{item_id:goods_id});
                }
            });
        }else{
            var confirmPopup = $ionicPopup.confirm({
                title: 'Confirm',
                template: 'Are you sure you want to complete this order?'
            });

            confirmPopup.then(function(res) {
                if(res) {
                    $rootScope.showLoading();
                    OrderService.completeOrder({order_id:order_id}).$promise.then(function (result) {
                        $rootScope.hideLoading();
                        $scope.result = result.data;
                        if(result.success == 1){
                            OrderStatusService.changeOrderStatus({orderid:order_id,order_status:'in_transit'}).$promise.then(function (res) {
                                console.log(res);
                            });
                            $rootScope.showAlert('Success',"You have completed this order.");
                        }
                        console.log($scope.result );
                    });
                }
            });
        }


    };

    $scope.deliveredOrder = function(order_id){
        var confirmPopup = $ionicPopup.confirm({
            title: 'Confirm',
            template: 'Are you sure you have delivered this order?'
        });

        confirmPopup.then(function(res) {
            if(res) {
                $rootScope.showLoading();
                OrderStatusService.changeOrderStatus({orderid:order_id,order_status:'delivered'}).$promise.then(function (res) {
                    $rootScope.hideLoading();
                    $scope.result = result.data;
                    if(result.success == 1){
                        $rootScope.showAlert('Success',"You have delivered this order.");
                    }else{
                        $rootScope.showAlert('Failure',result.error_msg);
                    }
                });
            }
        });

    };


})
.controller('GoodsDetailCtrl', function($scope,$stateParams,$rootScope,OrderService,OrderStatusService) {
    $rootScope.validateUser();
    $rootScope.showLoading();
    function showSub(pick_up,out_of_stock){
        var result = false;
        if($scope.item.substitute == 'Y'){
            if(!pick_up && !out_of_stock){
                result = true;

            }
        }
        return result;
    }

    OrderService.getItemDetail({item_id:$stateParams.item_id}).$promise.then(function (result) {
        $scope.out_of_stock = false;
        $scope.pick_up = false;
        $rootScope.hideLoading();
        $scope.item = result.data;
        if($scope.item.item_status == 'out_of_stock'){
            $scope.out_of_stock = true;
        }
        if($scope.item.item_status == 'pick_up'){
            $scope.pick_up = true;
        }
        if($scope.item.markup == 'false'){
            $scope.markup = false;
            $scope.markup_precent = 1;
        }else{
            $scope.markup = true;
            $scope.markup_precent = parseFloat($scope.item.store_price)/($scope.item.price);
            if ($scope.item.sub_price != null){
                $scope.item.sub_price = (($scope.item.sub_price) * ($scope.markup_precent)).toFixed(2);
            }
        }
        if($scope.item.store_price == '' || $scope.item.store_price == null){
            $scope.item.store_price = $scope.item.price;
        }
        $scope.showSub = showSub($scope.pick_up,$scope.out_of_stock);
        console.log($scope.item );
    });

    $scope.submitSub=function(item){
        $rootScope.showLoading();
        OrderService.setSubItem({item_id:item.item_id,sub_name:item.sub_name,sub_price:(item.sub_price/$scope.markup_precent).toFixed(2),sub_volume:item.sub_volume,markup:$scope.markup}).$promise.then(function (result) {
            $rootScope.hideLoading();
            $scope.result = result.data;
            if(result.success == 0){
                $rootScope.showAlert('Error',result.error_msg);
            }
            console.log($scope.result );
        });
        $scope.inProgress();
    }

    $scope.pickUp = function(pickUp){
        $rootScope.showLoading();
        if(pickUp){
            OrderService.setItemStatus({item_id:$stateParams.item_id,item_status:'pick_up'}).$promise.then(function (result) {
                $rootScope.hideLoading();
                $scope.result = result.data;
                if(result.success == 0){
                    $rootScope.showAlert('Error',result.error_msg);
                }
            });
        }else{
            OrderService.setItemStatus({item_id:$stateParams.item_id,item_status:''}).$promise.then(function (result) {
                $rootScope.hideLoading();
                $scope.result = result.data;
                if(result.success == 0){
                    $rootScope.showAlert('Error',result.error_msg);
                }
            });
        }
        $scope.pick_up = pickUp;
        $scope.showSub = showSub($scope.pick_up,$scope.out_of_stock);
        $scope.inProgress();
    }

    $scope.outOfStock = function(outOfStock){
        $rootScope.showLoading();
        if(outOfStock){
            OrderService.setItemStatus({item_id:$stateParams.item_id,item_status:'out_of_stock'}).$promise.then(function (result) {
                $rootScope.hideLoading();
                $scope.result = result.data;
                if(result.success == 0){
                    $rootScope.showAlert('Error',result.error_msg);
                }
            });
        }else{
            OrderService.setItemStatus({item_id:$stateParams.item_id,item_status:''}).$promise.then(function (result) {
                $rootScope.hideLoading();
                $scope.result = result.data;
                if(result.success == 0){
                    $rootScope.showAlert('Error',result.error_msg);
                }
            });
        }
        $scope.out_of_stock = outOfStock;
        $scope.showSub = showSub($scope.pick_up,$scope.out_of_stock);
        $scope.inProgress();
    }

    $scope.changeMarkUp = function(markup){
        $scope.markup = markup;
        if(markup){
            $scope.markup_precent = parseFloat($scope.item.store_price)/($scope.item.price);
        }else{
            $scope.markup_precent = 1;
        }
    }

    $scope.showMsg=function(msg){
        $rootScope.showAlert('Message',msg);
    }

    $scope.inProgress = function(){
        OrderStatusService.changeOrderStatus({orderid:$scope.item.order_id,order_status:'in_progress'}).$promise.then(function (result) {
            console.log(result);
        });
    }
})

;
